package com.powernode.customer.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.customer.mapper.CustomerInfoMapper;
import com.powernode.customer.mapper.CustomerLoginLogMapper;
import com.powernode.customer.service.CustomerInfoService;
import com.powernode.model.entity.customer.CustomerInfo;
import com.powernode.model.entity.customer.CustomerLoginLog;
import com.powernode.model.form.customer.UpdateWxPhoneForm;
import com.powernode.model.vo.customer.CustomerLoginVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {
    @Resource
    private WxMaService wxMaService;
    @Resource
    private CustomerLoginLogMapper customerLoginLogMapper;

    /**
     * <p>顾客登录</p>
     * <p>1. 获取用户的微信openId</p>
     * <p>2. 根据微信openId查询用户信息</p>
     * <p>3. 若用户信息不存在，则插入用户信息</p>
     *
     * @return 主键
     */
    @Override
    @Transactional
    public Long login(String code) {
        CustomerInfo customerInfo;
        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            String openid = sessionInfo.getOpenid();
            LambdaQueryWrapper<CustomerInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(CustomerInfo::getWxOpenId, openid);
            customerInfo = this.getOne(lambdaQueryWrapper);
            if (customerInfo == null) {
                customerInfo = new CustomerInfo();
                customerInfo.setWxOpenId(openid);
                customerInfo.setAvatarUrl("https://www.shanghairanking.cn/_uni/logo/86980791.png");
                customerInfo.setNickname("用户" + System.currentTimeMillis());
                customerInfo.setCreateTime(new Date());
                this.save(customerInfo);
            }
            // 记录登录日志
            CustomerLoginLog customerLoginLog = new CustomerLoginLog();
            customerLoginLog.setCustomerId(customerInfo.getId());
            customerLoginLog.setMsg("微信小程序登录");
            customerLoginLog.setCreateTime(new Date());
            customerLoginLogMapper.insert(customerLoginLog);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        return customerInfo.getId();
    }

    /**
     * 获取用户信息
     */
    @Override
    public CustomerLoginVo getCustomerLoginInfo(Long customerId) {
        CustomerInfo customerInfo = getById(customerId);
        CustomerLoginVo customerLoginVo = new CustomerLoginVo();
        BeanUtils.copyProperties(customerInfo, customerLoginVo);
        boolean isBindPhone = StringUtils.hasText(customerInfo.getPhone());
        customerLoginVo.setIsBindPhone(isBindPhone);
        return customerLoginVo;
    }

    /**
     * 获取用户手机号
     */
    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
        try {
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(updateWxPhoneForm.getCode());
            String phoneNumber = phoneNoInfo.getPhoneNumber();
            CustomerInfo customerInfo = new CustomerInfo();
            customerInfo.setId(updateWxPhoneForm.getCustomerId());
            customerInfo.setPhone(phoneNumber);
            return this.updateById(customerInfo);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }
}